#!/usr/bin/python
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
from os import curdir, sep
import cgi, urllib, urlparse

PORT_NUMBER = 8080


#This class will handles any incoming request from
#the browser 
class myHandler(BaseHTTPRequestHandler):
	
	#Handler for the GET requests
	def do_GET(self):
		query = urlparse.urlparse(self.path).query
		if query != '':
			query_components = urlparse.parse_qs(query)
			if 'url' in query_components:
				self.send_response(200)
				self.send_header('Content-type', 'text/xml')
				self.end_headers()
				url_to_get = query_components['url'][0]
				url_contents = urllib.urlopen(url_to_get).read()
				self.wfile.write(url_contents)
				return

		if self.path=="/": self.path="/index.html"

		startIndex = self.path.find('?')
		if startIndex != -1:
			self.path = self.path[0:startIndex]

		try:
			#Check the file extension required and
			#set the right mime type

			sendReply = False
			if self.path.endswith(".html"):
				mimetype='text/html'
				sendReply = True
			elif self.path.endswith(".jpg"):
				mimetype='image/jpg'
				sendReply = True
			elif self.path.endswith(".gif"):
				mimetype='image/gif'
				sendReply = True
			elif self.path.endswith(".png"):
				mimetype='image/png'
				sendReply = True
			elif self.path.endswith(".js"):
				mimetype='application/javascript'
				sendReply = True
			elif self.path.endswith(".css"):
			     	mimetype='text/css'
			     	sendReply = True
			elif '.woff' in self.path:
				mimetype = 'application/x-font-woff'
				sendReply = True
			elif self.path.endswith('.svg'):
				mimetype = 'image/svg+xml'
				sendReply = True
			else:
			 	mimetype = 'application/octet-stream'
			 	sendReply = True



			if sendReply == True:
				#Open the static file requested and send it
				f = open(curdir + sep + self.path) 
				self.send_response(200)
				self.send_header('Content-type',mimetype)
				self.end_headers()
				self.wfile.write(f.read())
				f.close()
			return

		except IOError:
			self.send_error(404,'File Not Found: %s' % self.path)
			
try:
	#Create a web server and define the handler to manage the
	#incoming request
	server = HTTPServer(('', PORT_NUMBER), myHandler)
	print 'Started httpserver on port ' , PORT_NUMBER
	
	#Wait forever for incoming htto requests
	server.serve_forever()

except KeyboardInterrupt:
	print '^C received, shutting down the web server'
	server.socket.close()

